package com.free.mini.gateway.utils;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.free.mini.common.base.ResultData;
import com.free.mini.gateway.config.ApiKeysConfig;
import com.free.mini.gateway.utils.encryption.AES;
import com.free.mini.gateway.utils.encryption.SignatureUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DataDealUtil {


    /**
     * 根据版本号解密
     *
     * @param data
     * @param clazz
     * @param needUrlEncoder
     * @param apiKeysConfig
     * @param <T>
     * @return
     */
    public static <T> T decrypt(String data, Class<T> clazz, boolean needUrlEncoder, ApiKeysConfig apiKeysConfig) {
        String jsonStr = SignatureUtil.checkSign(data, needUrlEncoder, apiKeysConfig);
        if (jsonStr == null || jsonStr.length() <= 0) {
            log.info("version code:[{}],response data :[{}]", apiKeysConfig.getVersionCode(), jsonStr);
            throw new RuntimeException("parameter error");
        }
        try {
            return JSON.parseObject(jsonStr, clazz);
        } catch (Exception e) {
            log.error("参数解密错误:{}", e);
            throw new RuntimeException("parameter decrypt error");
        }
    }



    public static ResultData encrypt(ResultData resultData, boolean needUrlEncoder, ApiKeysConfig apiKeysConfig) {
        try {
            if (resultData == null) {
                return null;
            }
            if (resultData.getData() == null) {
                Map map = new HashMap();
                map.put("serverTime", System.currentTimeMillis());
                resultData.setData(map);
            }
            resultData.setData(AES.encryptAES(JSON.toJSONString(resultData.getData()), needUrlEncoder, apiKeysConfig));
            log.debug("DataDealUtil最后返回加密参数{}:", resultData.toJSON());
            log.debug("new secret DataDealUtil result{}:", resultData.toJSON());
            return resultData;
        } catch (Exception e) {
            log.error("响应加密错误:{}", e);
            throw new RuntimeException("response encrypt error");
        }
    }

}
